import React, {ChangeEvent} from 'react';
import {Button, Input, message, Space} from "antd";
import {loginApi} from '@/api/Login.ts';

class LoginForm extends React.Component {
    constructor(props: NonNullable<unknown>) {
        super(props);
        // 初始化状态
        this.state = {
            username: '',
            password: '',
        };
    }

    // 处理输入字段变化的函数
    handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        // 更新状态
        this.setState({
            [name]: value,
        });

        console.log(name, value);
    }

    // 处理登录的函数
    handleLogin = async () => {
        // 判断必填
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        if (!this.state.username.trim() || !this.state.password.trim()) {
            alert('请输入用户名');
            return;
        }
        // 在这里添加登录逻辑
        // console.log('New Login with:', this.state);
        await loginApi({
            username: this.state.username,
            password: this.state.password,
        }).then((res) => {
            if (res.code === 400) {
                message.error(res.msg);
            }else{
                // 提示登录成功
                message.success(res.msg);
                // 保存token
                localStorage.setItem('lege-token', res.data.token);
                // 跳转到/index
                // 清空临时数据(可选)
            }
            console.log(res);
        });
    }

    render() {
        return (
            <>
                <Space direction="vertical" size="large" style={{ display: 'flex' }}>
                    <Input name="username" placeholder="用户名" onChange={this.handleInputChange} />
                    <Input.Password name="password" placeholder="密码" onChange={this.handleInputChange}/>
                    {/* 验证码盒子 */}
                    <Button type="primary" className="loginBtn" onClick={this.handleLogin} block>登录</Button>
                </Space>
            </>
        )
    }
}

export default LoginForm;